﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TicketsWizards
{
    public partial class Form3 : Form
    {
        bool isLogIn = false;

        static string userName = string.Empty;//
        static string pwd = string.Empty;//

        public Form3()
        {
            InitializeComponent();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                //回车
                Navto();
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            Navto();
        }

        private void Navto()
        {
            var url = textBox1.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                url = "https://dynamic.12306.cn/otsweb/logonaction?method=init";
            }
            webBrowser1.Navigate(url);
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            userName = AppConfigHelper.GetAppConfig("username");
            pwd = AppConfigHelper.GetAppConfig("password");

            webBrowser1.ScriptErrorsSuppressed = true;

            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            Navto();
        }

        HtmlDocument ifm;//= webBrowser1.Document.Window.Frames["main"].Document;
        HtmlElement ctrUserName;// = ifm.GetElementById("username");
        HtmlElement ctrPwd;// = ifm.GetElementById("password");
        HtmlElement ctrRandcode;

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //  ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

            if (!isLogIn)
            {
                try
                {
                    ifm = webBrowser1.Document.Window.Frames["main"].Document;
                    ctrUserName = ifm.GetElementById("username");
                    ctrPwd = ifm.GetElementById("password");
                    ctrRandcode = ifm.GetElementById("randCode");
                    InitAndLogOn();

                    if (ifm.DomDocument != null)
                    {
                        InstallScriptFile(ifm);
                    }
                }
                catch { }
            }
        }

        void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {

            // Ignore the error and suppress the error dialog box. 
            e.Handled = true;
        }

        private void InitAndLogOn()
        {
            if (ctrUserName != null)
            {
                // ctrUserName.SetAttribute("value", string.Empty);
                // System.Threading.Thread.Sleep(300);
                // ctrUserName.Focus();
                ctrUserName.SetAttribute("value", userName);
                // SendKeys.Send(userName);
                // SendKeys.Send("{tab}");
                // System.Threading.Thread.Sleep(300);
                //Application.DoEvents();
                // ctrPwd.Focus();
                ctrPwd.SetAttribute("value", pwd);
                //  Application.DoEvents();
                // SendKeys.Send(pwd);
                //  Application.DoEvents();
                // System.Threading.Thread.Sleep(300);



                ctrRandcode.SetAttribute("value", "");
                ctrRandcode.Focus();
                webBrowser1.Update();
                Application.DoEvents();
                //  System.Threading.Thread.Sleep(300);
                //SendKeys.Send("{enter}");
                //string tmp = "";
                // tmp = ifm.GetElementById("password").GetAttribute("value");
                // MessageBox.Show(tmp);                
            }
        }

        private void InstallScriptFile(HtmlDocument frameDoc = null)
        {
            InstallScript(url: new Uri("https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"), frameDoc: frameDoc);

            string autologonfilepath = Constants.ApplicationStartUpPath + "\\UserScript\\12306AutoLogin.user.js";
            string autoqueryfilepath = Constants.ApplicationStartUpPath + "\\UserScript\\12306query.user.js";

            string logonScript = FileHelper.GetFileContent(autologonfilepath);
            string queryScript = FileHelper.GetFileContent(autoqueryfilepath);

            InstallScript(code: logonScript, frameDoc: frameDoc);
            InstallScript(code: queryScript, frameDoc: frameDoc);

            ctrRandcode.Focus();
            webBrowser1.Update();
            Application.DoEvents();

        }

        /// <summary>
        /// 在 WebBrowser子框架中增加 script 标签, 并添加定义的javascript代码 或 指定脚本的地址
        /// </summary>
        /// <param name="code">javascript 代码</param>
        /// <param name="url">脚本地址, 如: "http://www.google.com/xxx.js"</param>
        /// <param name="frameDoc">将加入代码的框架</param>
        private void InstallScript(string code = "", Uri url = null, HtmlDocument frameDoc = null)
        {
            HtmlDocument doc = frameDoc;
            if (frameDoc == null)
            {
                doc = this.webBrowser1.Document;
            }
            HtmlElement newElement = null;
            newElement = doc.CreateElement("script");
            //newElement.SetAttribute( "id", MakeKey() );
            newElement.SetAttribute("type", "text/javascript");
            newElement.SetAttribute("language", "javascript");
            if (url == null)
                newElement.SetAttribute("text", code);
            else
                newElement.SetAttribute("src", url.AbsoluteUri);
            try
            {
                doc.GetElementsByTagName("head")[0].AppendChild(newElement);
            }
            catch { }
        }

    }
}
